<template>
  <div class="app-container">
    <B class="flex-center" style="margin-left: -50px" >车辆控制</B>
    <div class="flex-center">
      <div style="width: 300px;">
        <el-row style="margin-top: 100px">
          <el-col :span="6">
            <img v-if="door==1" height="60" src="../../assets/image/opendoor.png" style="cursor: pointer" width="60"
                 @click="changeDoor"/>
            <img v-else height="60" src="../../assets/image/closedoor.png" style="cursor: pointer" width="60"
                 @click="changeDoor"/>
          </el-col>
          <el-col :span="18" style="display: flex; align-items: center;">
            <span v-if="door==1">关闭车门</span>
            <span v-else>打开车门</span>
          </el-col>
        </el-row>
        <el-row style="margin-top: 100px">
          <el-col :span="6">
            <img v-if="light==1" height="60" src="../../assets/image/openlight.png" style="cursor: pointer" width="60"
                 @click="changeLight"/>
            <img v-else height="60" src="../../assets/image/closelight.png" style="cursor: pointer" width="60"
                 @click="changeLight"/>
          </el-col>
          <el-col :span="18" style="display: flex; align-items: center;">
            <span v-if="light==1">关闭车灯</span>
            <span v-else>打开车灯</span>
          </el-col>
        </el-row>
      </div>
      <img v-if="door == '0' && light == '0'" height="575" src="../../assets/image/car.png" width="344"/>
      <img v-else-if="door == '1' && light == '0'" height="575" src="../../assets/image/carOD.png" width="344"/>
      <img v-else-if="door == '0' && light == '1'" height="575" src="../../assets/image/carOL.png" width="344"/>
      <img v-else height="575" src="../../assets/image/carOLD.png" width="344"/>
      <div class="control">
        <el-row border="1">
          <el-col :span="8" class="fang">
          </el-col>
          <el-col :span="8" class="fang">
            <img :src="up" height="64" style="cursor: pointer" width="64"
                 @mousedown="handleMouseDown('up')"
                 @mouseenter="handleMouseOver('up')"
                 @mouseleave="handleMouseLeave('up')"
                 @mouseup="handleMouseUp('up')"/>
          </el-col>
          <el-col :span="8" class="fang">
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" class="fang">
            <img :src="left" height="64" style="cursor: pointer" width="64"
                 @mousedown="handleMouseDown('left')"
                 @mouseenter="handleMouseOver('left')"
                 @mouseleave="handleMouseLeave('left')"
                 @mouseup="handleMouseUp('left')"/>
          </el-col>
          <el-col :span="8" class="fang">
            <img height="64" src="../../assets/image/middle.png" width="64"/>
          </el-col>
          <el-col :span="8" class="fang">
            <img :src="right" height="64" style="cursor: pointer" width="64"
                 @mousedown="handleMouseDown('right')"
                 @mouseenter="handleMouseOver('right')"
                 @mouseleave="handleMouseLeave('right')"
                 @mouseup="handleMouseUp('right')"/>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" class="fang">
          </el-col>
          <el-col :span="8" class="fang">
            <img :src="down" height="64" style="cursor: pointer" width="64"
                 @mousedown="handleMouseDown('down')"
                 @mouseenter="handleMouseOver('down')"
                 @mouseleave="handleMouseLeave('down')"
                 @mouseup="handleMouseUp('down')"/>
          </el-col>
          <el-col :span="8" class="fang">
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script name="control" setup>
import {getCurrentInstance, onUnmounted, ref} from 'vue';
import {getCarState, stop, turnback, turnleft, turnmove, turnright, updateState, updateLight, updateDoor} from "@/api/carInfo/control";

const route = useRoute();
const {proxy} = getCurrentInstance();
const carId = route.params.id ? route.params.id : route.query.id;

const door = ref("0");
const light = ref("0");
let socket;

const upImage = new URL('../../assets/image/up.png', import.meta.url).href;
const upImageCover = new URL('../../assets/image/up-over.png', import.meta.url).href;
const upImageClick = new URL('../../assets/image/up-click.png', import.meta.url).href;
const up = ref(upImage);

const downImage = new URL("../../assets/image/down.png", import.meta.url).href;
const downImageCover = new URL("../../assets/image/down-over.png", import.meta.url).href;
const downImageClick = new URL("../../assets/image/down-click.png", import.meta.url).href;
const down = ref(downImage);

const leftImage = new URL("../../assets/image/left.png", import.meta.url).href;
const leftImageCover = new URL("../../assets/image/left-over.png", import.meta.url).href;
const leftImageClick = new URL("../../assets/image/left-click.png", import.meta.url).href;
const left = ref(leftImage);

const rightImage = new URL("../../assets/image/right.png", import.meta.url).href;
const rightImageCover = new URL("../../assets/image/right-over.png", import.meta.url).href;
const rightImageClick = new URL("../../assets/image/right-click.png", import.meta.url).href;
const right = ref(rightImage);

/**
 * 控制门
 */
function changeDoor() {
  if (door.value == "1") {
    door.value = "0";
  } else {
    door.value = "1";
  }
  updateDoor({carId: carId, door: door.value}).then(response => {
  }).catch(() => {
  });
}

/**
 * 控制灯
 */
function changeLight() {
  if (light.value == "1") {
    light.value = "0";
  } else {
    light.value = "1";
  }
  updateLight({carId: carId, light: light.value}).then(response => {
  }).catch(() => {
  })
}

function handleMouseOver(type) {
  if (type == 'up') {
    up.value = upImageCover;
  } else if (type == 'down') {
    down.value = downImageCover;
  } else if (type == 'left') {
    left.value = leftImageCover;
  } else if (type == 'right') {
    right.value = rightImageCover;
  }
}

function handleMouseLeave(type) {
  if (type == 'up') {
    up.value = upImage;
  } else if (type == 'down') {
    down.value = downImage;
  } else if (type == 'left') {
    left.value = leftImage;
  } else if (type == 'right') {
    right.value = rightImage;
  }
}


// 返回按钮
function handleClose() {
  const obj = {path: "/carManage"};
  proxy.$tab.closeOpenPage(obj);
}

function handleMouseDown(type) {
  if (type == 'up') {
    up.value = upImageClick;
    turnmove(carId);
  } else if (type == 'down') {
    down.value = downImageClick;
    turnback(carId)
  } else if (type == 'left') {
    left.value = leftImageClick;
    turnleft(carId)
  } else if (type == 'right') {
    right.value = rightImageClick;
    turnright(carId)
  }
}

function handleMouseUp(type) {
  if (type == 'up') {
    up.value = upImage;
  } else if (type == 'down') {
    down.value = downImage;
  } else if (type == 'left') {
    left.value = leftImage;
  } else if (type == 'right') {
    right.value = rightImage;
  }
  stop(carId);
}

function init() {
  getCarState(carId).then(response => {
    door.value = response.data.door;
    light.value = response.data.light;
  });
  let hostname = window.location.hostname;
  console.log("browser hostname:" + hostname);
  socket = new WebSocket('ws://' + hostname + ':8088/webSocket/'+ carId + new Date().getTime()); // 替换为你的 WebSocket 服务器地址和token

  socket.onopen = () => {
    console.log('WebSocket 连接已建立');
    // 在连接建立后，可以发送消息或执行其他操作
  };

  socket.onmessage = (event) => {
    console.log('收到消息:', event.data);
    let msg = JSON.parse(event.data.toString())
    if (msg.carId == carId) {
      light.value = msg.light;
      door.value = msg.door;
    }
    // 处理收到的消息数据
  };

  socket.onclose = () => {
    console.log('WebSocket 连接已关闭');
    // 在连接关闭后，可以执行清理操作或重新连接等处理
  };

}

onUnmounted(()=>{
  socket.close();
})

// function createConnection() {
//   let connectUrl = "ws://127.0.0.1:8088/webSocket/";
//   let client = mqtt.connect(connectUrl, options);
//   client.on("connect", () => {
//     console.log("连接成功!");
//     //订阅
//     // client.subscribe("car_state", 2, (error, res) => {
//     //   if (error) {
//     //     console.log("subscribe to topics error", error);
//     //     return;
//     //   }
//     //   console.log("Subscribe to topics res", res);
//     // });
//   });
//   client.on("error", (error) => {
//     console.log("Connection failed", error);
//   });
//   //获取消息
//   client.on("message", (topic, message) => {
//     let msg = JSON.parse(message.toString())
//     if (msg.carId == carId) {
//       light.value = msg.light;
//       door.value = msg.door;
//     }
//   });
// }

// createConnection();
init();
</script>

<style>
.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.control {
  margin-top: 100px;
  width: 240px;
  margin-left: 100px;
  background-image: url('@/assets/image/yuan.png');
  background-repeat: no-repeat;
  background-size: 100%;
}

.fang {
  width: 80px;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
